/* eslint-disable max-lines */
/**
 * 入参
 *  type：1-指令新增   2-簿记新增    3-详情  4-交收
    info：type=3||4时，需回填字段
    onRef：组件指针
    getInfo：通过onRef，调用getInfo方法，获取各字段的值，在getInfo中完成校验，若校验不通过，返回undefined
    reset：通过onRef，调用reset方法，清空页面字段
    productOnChange：产品变更事件，输出当前产品ID，若无则为undefined；
    portfolioOnChange：组合变更事件，输出当前组合ID，若无则为undefined；
    tradingcodeOnChange：证券代码变更事件，输出当前证券code，若无则为undefined。
 */
import React, { PureComponent } from 'react';
import { DATA_ENTRY, FormGroup, codeType } from '../../../../components';
import moment from 'moment';
import style from './index.less';
import { connect } from 'dva';
import investmentType from '../../../../utils/enumeratedValues/investmentType';
import { calculateFee } from '../../../../utils/commonFunc';
import { times } from 'number-precision';

class OrderFormC extends PureComponent {
  static defaultProps = {
    onRef: () => {},
    portfolioOnChange: () => {},
    productOnChange: () => {},
    tradingcodeOnChange: () => {},
    workStation: false,
  };

  formGroupRef = React.createRef(); // formGroup组件本身

  state = {
    info: undefined, // etf详情
    type: undefined, // 当前指令的类型type：1-指令新增   2-簿记新增    3-簿记详情
    SecuritiesCode: undefined, // 证券代码val值
    portfolioCode: undefined,
    bussniessVisible: false, // 业务目标编辑补充是否可见
    addSPPIFlag: false, // 点击了新增测试按钮
    SPPI_result: undefined, // 根据证券代码获取sppi结果
    objectives: undefined, // 选中的业务目标
    objectivesEditObj: {}, // 缓存每一个业务目标对应的编辑
    editContent: {}, // 业务目标编辑内容
    investmentTypeList: [...investmentType], // 投资类型下拉
    tradeDirect: '1', // 交易方向
    feeData: {
      // 费用自动计算条件
      tradingCode: undefined,
      sectype: 'fb',
      sectypeii: undefined,
      orderside: undefined,
      price: undefined,
    },
  };

  componentDidMount() {
    this.props.onRef(this);
    if (this.props.type == '3' || this.props.type == '4') {
      // 详情时取业务目标的值
      this.setState({
        objectives: this.props.info ? this.props.info.bussinessObjectives : undefined,
        editContent: this.props.info || {},
        tradeDirect: this.props.info ? this.props.info.direction : '1',
      });
    }
    if (this.props.type == 12) {
      this.setState({ feeData: { ...this.state.feeData, groupId: undefined } });
    } else {
      this.setState({ feeData: { ...this.state.feeData, productId: undefined, portfolioid: undefined } });
    }
  }

  // 费用自动计算 暂时没有用上
  changeFee = (type, data) => {
    const { setFieldsValue } = this.formGroupRef.current.formRef.current;
    if (this.props.type == 3 || this.props.type == 4) return; // 详情不计算
    setTimeout(() => {
      if (data == undefined) {
        setFieldsValue({ fee: undefined });
        if (type == 'tradingCode') {
          this.setState({ feeData: { ...this.state.feeData, tradingCode: undefined, sectypeii: undefined } });
        } else if (type == 'productId') {
          this.setState({ feeData: { ...this.state.feeData, productId: undefined, portfolioid: undefined } });
        } else {
          this.setState({ feeData: { ...this.state.feeData, [type]: undefined } });
        }
      } else if (type == 'tradingCode') {
        this.setState({ feeData: { ...this.state.feeData, tradingCode: data.tradingCode, sectypeii: data.assetType } }, () => {
          const fee = calculateFee(this.state.feeData, !!(this.props.type == 10 || this.props.type == 12));
          fee.then((r) => {
            setFieldsValue({ fee: r });
          });
        });
      } else {
        this.setState({ feeData: { ...this.state.feeData, [type]: data } }, () => {
          const fee = calculateFee(this.state.feeData, !!(this.props.type == 10 || this.props.type == 12));
          fee.then((r) => {
            setFieldsValue({ fee: r });
          });
        });
      }
    }, 100);
  };

  // 组合改变
  groupOnChange = (value) => {
    this.setState(
      {
        portfolioCode: value?.info?.portfolioCode,
      },
      () => {
        this.getInterest();
      },
    );
    // 抛出组合id
    let val;
    if (value) val = value.key;
    this.props.portfolioOnChange(val);
  };

  // 产品改变
  productOnChange = (value) => {};

  // 计算交易总额
  calculateAmount = (val, types) => {
    const { getFieldValue, setFieldsValue } = this.formGroupRef.current.formRef.current;
    const { type } = this.props;
    let price, amount;
    const direction = getFieldValue('direction');
    const interest = getFieldValue('interest') ?? '';
    if (types != 'amount') {
      price = val ?? '';
      amount = getFieldValue('amount') ?? '';
      if (type == 2 && direction == 2) {
        if (price !== '' && amount !== '' && interest !== '') {
          setFieldsValue({
            [types]: Number(times(price || 0 + interest || 0, amount).toFixed(2)),
          });
        } else {
          setFieldsValue({
            [types]: undefined,
          });
        }
      } else if (price !== '' && amount !== '') {
        setFieldsValue({
          [types]: Number(times(price || 0, amount || 0).toFixed(2)),
        });
      } else {
        setFieldsValue({
          [types]: undefined,
        });
      }
    } else {
      // 数量变更 净价总额 全价总额都进行变更
      amount = val ?? '';
      price = getFieldValue('price') ?? '';
      if (type == 2 && direction == 2) {
        if (price !== '' && amount !== '' && interest !== '') {
          setFieldsValue({
            parValueTotal: Number(times(price || 0 + interest || 0, amount || 0).toFixed(2)),
          });
        } else {
          setFieldsValue({
            parValueTotal: undefined,
          });
        }
      } else if (price !== '' && amount !== '') {
        setFieldsValue({
          parValueTotal: Number(times(price || 0, amount || 0).toFixed(2)),
        });
      } else {
        setFieldsValue({
          parValueTotal: undefined,
        });
      }
      // this.changeFee('price', (price || 0) * amount);
    }
  };

  // 证券代码切换
  securitiesCodeChange = (value) => {
    const {
      form,
      user: { currentUser },
      info,
    } = this.props;
    if (info) return; // 详情时不进入判断
    this.setState(
      {
        SecuritiesCode: value,
      },
      () => {
        this.getSPPI_Result();
        this.getInterest();
      },
    );
    this.props.tradingcodeOnChange(value);
  };

  // 获取sppi结果
  getSPPI_Result = () => {
    const { SecuritiesCode } = this.state;
    if (this.props.type < 3 || this.props.type == 12) {
      if (!SecuritiesCode) {
        this.setState(
          {
            SPPI_result: undefined,
          },
          () => {
            this.formGroupRef.current.formRef.current.setFieldsValue({
              SPPI_result: this.state.SPPI_result,
            });
            this.setSelectList();
          },
        );
        return;
      }
      this.props.dispatch({
        type: 'bondTradeM/getSPPIResult',
        payload: {
          exchangeCode: SecuritiesCode.exchangeCode,
          tradingCode: SecuritiesCode.tradingCode,
        },
        callback: (data) => {
          let temp;
          if (data) {
            // sppi有值 不可点击新增按钮  无值可以
            temp = data.rgpd;
          } else {
            temp = undefined;
          }
          this.setState(
            {
              SPPI_result: temp,
            },
            () => {
              this.formGroupRef.current.formRef.current.setFieldsValue({
                SPPI_result: this.state.SPPI_result,
              });
              this.setSelectList();
            },
          );
        },
      });
    }
  };

  // 设置投资类型下拉 并确定默认值
  setSelectList = () => {
    // 以收取该金融资产合同现金流量为目的	是	AC
    // 以收取该金融资产合同现金流量为目的	否	FVTPL
    // 以收取该合同现金流量及出售金融资产为目的	是	FVOCI
    // 以收取该合同现金流量及出售金融资产为目的	否	FVTPL
    // 其他	是 or 否	FVTPL
    const { setFieldsValue } = this.formGroupRef.current.formRef.current;
    const { SPPI_result, objectives, tradeDirect } = this.state;
    if (tradeDirect == '1') {
      // 交易方向为买入
      if (SPPI_result == undefined || objectives == undefined) {
        setFieldsValue({
          investmentType: undefined,
        });
        this.setState({
          investmentTypeList: investmentType,
        });
        return;
      }
      let arr = [];
      if (objectives == 1 && SPPI_result == 1) {
        // AC
        arr = [{ value: 'AC', title: 'AC' }];
        setFieldsValue({
          investmentType: 'AC',
        });
      } else if ((objectives == 1 && SPPI_result == 2) || (objectives == 2 && SPPI_result == 2) || (objectives == 4 && SPPI_result)) {
        // FVTPL
        arr = [{ value: 'FVTPL', title: 'FVTPL' }];
        setFieldsValue({
          investmentType: 'FVTPL',
        });
      } else if (objectives == 2 && SPPI_result == 1) {
        // FVOCI
        arr = [{ value: 'FVOCI', title: 'FVOCI' }];
        setFieldsValue({
          investmentType: 'FVOCI',
        });
      } else {
        arr = [...investmentType];
        setFieldsValue({
          investmentType: undefined,
        });
      }
      this.setState({
        investmentTypeList: [...arr],
      });
    } else if (tradeDirect == '2') {
      // 交易方向卖出 请求新的接口
      this.setState({
        investmentTypeList: [...investmentType],
      });
      setTimeout(() => {
        setFieldsValue({
          investmentType: this.props.investmentType,
        });
      }, 500);
    }
  };

  // 业绩目标修改
  changeObjectives = (e) => {
    this.setState(
      {
        objectives: e,
      },
      () => {
        this.setSelectList();
      },
    );
  };

  // 获取当前表单数据 并校验
  getInfo = async () => {
    const {
      user: { currentUser },
      type,
    } = this.props;
    let query;
    const { objectives, objectivesEditObj } = this.state;
    const obj = objectivesEditObj[objectives];
    const formValues = await this.formGroupRef.current.getFormGroupData();
    // 若校验不通过后面的代码不会被执行
    query = formValues;
    query.userid = currentUser.userId;
    query.username = currentUser.name;
    query.tradingcode = this.state.SecuritiesCode.tradingCode;
    query.secuabbr = this.state.SecuritiesCode.secuabbr;
    query.exchangeCode = this.state.SecuritiesCode.exchangeCode;
    query.sppiResult = query.SPPI_result; // 修改入参名
    // 非标簿记 新增利息到账日
    if (type == 2 && query.direction == '2' && query.interestArrivalDate) {
      query.interestArrivalDate = query.interestArrivalDate.format('YYYY-MM-DD');
    }
    if (this.props.type != 10 && this.props.type != 12) query.fee = 0; // 费用计算逻辑未完全梳理清楚，后续用户有真正需求时再添加费用计算相关逻辑
    delete query.SPPI_result;
    delete query.zlxdr;
    delete query.zqdm;
    if (obj) query = { ...query, ...obj };
    return query;
  };

  // 重置页面数据 取消
  reset = () => {
    this.props.portfolioOnChange(undefined);
    this.props.tradingcodeOnChange(undefined); // 重置组合id和证券代码
    this.formGroupRef.current.resetFields(); // 通过formGroupRef重置表单

    this.setState({
      bussniessVisible: false, // 业务目标编辑补充是否可见
      addSPPIFlag: false, // 点击了新增测试按钮
      SPPI_result: undefined, // 根据证券代码获取sppi结果
      objectives: undefined, // 选中的业务目标
      objectivesEditObj: {}, // 缓存每一个业务目标对应的编辑
      editContent: {}, // 业务目标编辑内容
      investmentTypeList: [...investmentType], // 投资类型下拉
      tradeDirect: '1', // 交易方向
      SecuritiesCode: undefined,
      portfolioCode: undefined,
    });
  };

  directionChange = (e) => {
    const { info } = this.props;
    if (info) return;
    const { setFieldsValue } = this.formGroupRef.current.formRef.current;
    // this.changeFee('orderside', e?.value);
    this.setState(
      {
        tradeDirect: e.value,
      },
      () => {
        this.getInterest();
        if (this.props.type < 3 || this.props.type == 12) {
          // 交易方向改变 对投资类型的影响 1买入 2卖出
          this.setSelectList();
        }
      },
    );
    if (e) {
      setFieldsValue({
        parValueTotal: undefined,
        price: undefined,
      });
      // this.changeFee('price', undefined);
    }
  };

  // 获取利息
  getInterest = () => {
    const { setFieldsValue, getFieldValue } = this.formGroupRef.current.formRef.current;
    const { tradeDirect, portfolioCode, SecuritiesCode } = this.state;
    const { type, dispatch } = this.props;
    // 簿记 交易方向为卖出
    if (type == 2 && tradeDirect === '2' && portfolioCode && SecuritiesCode?.tradingCode) {
      dispatch({
        type: 'nonstandardOrderM/getInterest',
        payload: {
          miniUnitId: portfolioCode,
          tradingCode: SecuritiesCode.tradingCode,
        },
        callback: (res) => {
          const price = getFieldValue('price') ?? '';
          const amount = getFieldValue('amount') ?? '';
          const interest = res ?? '';
          setFieldsValue({
            interest: res,
          });
          if (interest !== '' && price !== '' && amount !== '') {
            setFieldsValue({
              parValueTotal: (interest + price) * amount,
            });
          } else {
            setFieldsValue({
              parValueTotal: undefined,
            });
          }
        },
      });
    }
  };

  // 利息变更更改交易总额
  interestChange = (val) => {
    const { getFieldValue, setFieldsValue } = this.formGroupRef.current.formRef.current;
    const price = getFieldValue('price') ?? '';
    const amount = getFieldValue('amount') ?? '';
    const interest = val ?? '';
    if (interest !== '' && price !== '' && amount !== '') {
      setFieldsValue({
        parValueTotal: times(interest || 0 + price || 0, amount || 0),
      });
    } else {
      setFieldsValue({
        parValueTotal: undefined,
      });
    }
  };

  // form表单渲染
  formRender = () => {
    const {
      type,
      info,
      user: { currentUser },
      workStation,
      wproductid,
      wportfolioid,
    } = this.props;
    const { SPPI_result, SecuritiesCode, investmentTypeList, tradeDirect } = this.state;
    const {
      globalM: {
        dataDictionary: { SPPI_USER_DEFINEDTYPE = [] },
      },
    } = this.props;
    const tenant = localStorage.getItem('antd-pro-tenant');
    // 簿记之外
    const isBookkeeping = type == '1' || type == '10' || type == '11' || type == '12';
    let disabled;
    if (type == 1 || type == 2 || type == 10 || type == 11 || type == 12) {
      disabled = false;
    } else {
      disabled = true;
    }
    const zlxdr = `${currentUser.userId}-${currentUser.name}`;
    return (
      <FormGroup
        dataSource={[
          type == 10
            ? {
                dataIndex: 'portfolioid',
                type: DATA_ENTRY.SERIESPRODUCTGROUP,
                initialValue: this.props.listId,
                disabled: true,
                rules: [{ required: true, message: '请选择系列产品!' }],
                span: 24,
              }
            : type == 12
            ? {
                dataIndex: 'productGroupId',
                type: DATA_ENTRY.PRODUCTGROUP,
                rules: [{ required: true, message: '请选择产品组!' }],
                onChange: (e) => {
                  this.props.productGroupOnChange(e?.key); // 向外抛处组合id
                  // this.changeFee('groupId', e?.key);
                },
                span: 12,
                tradeModel: ['BOOKKEEPING_MODE', 'COMMAND_MODE'], // 不包含估值解析和估值对接的产品
              }
            : {
                disabled,
                title: ['产品', '组合'],
                type: DATA_ENTRY.PRODUCTGROUPSEP,
                initialValue: workStation ? [wproductid, wportfolioid] : info ? [info.productid, info.portfolioid] : undefined,
                authority: 'write',
                multipleGroup: false,
                dataIndex: ['productid', 'portfolioid'],
                rules: [[{ required: true, message: '请选择产品!' }], [{ required: true, message: '请选择组合!' }]],
                initChangeFlag: workStation === true,
                groupOnChange: (e) => {
                  this.groupOnChange(e);
                  // this.changeFee('portfolioid', e?.key);
                  this.props.portfolioCode(e); // 向外抛出组合code
                },
                productOnChange: (e) => {
                  this.productOnChange(e);
                  // this.changeFee('productId', e?.key);
                  this.props.productCode(e); // 向外抛出产品code
                },
                allowClear: false,
                exist: 1,
                span: 24,
                direction: workStation ? 'columns' : 'row',
                tradeModel: workStation ? undefined : type == 1 || type == 2 ? ['BOOKKEEPING_MODE', 'COMMAND_MODE'] : undefined,
                workStation,
                onRef: (ref) => (this.productRef = ref),
              },
          {
            dataIndex: 'zqdm',
            title: '证券代码',
            type: DATA_ENTRY.SECURITIESCODE,
            initialValue: info ? `${info.exchangeCode}-${info.tradingcode}` : undefined,
            onChange: (e) => {
              this.securitiesCodeChange(e);
              // this.changeFee('tradingCode', e ? e : undefined);
            },
            codeType: codeType.fb,
            rules: [{ required: true, message: '请选择证券代码!' }],
            disabled,
            span: workStation ? 24 : 12,
          },
          {
            title: '交易方向', // 显示名称
            dataIndex: 'direction', // Form识别的Item ID
            businessType: '12',
            type: DATA_ENTRY.TRADINGDIRECT,
            initialValue: info ? info.direction : undefined,
            disabled,
            onChange: this.directionChange,
            allowClear: false,
            rules: [{ required: true, message: '请选择交易方向!' }],
            span: workStation ? 24 : 12,
          },
          {
            hide: tradeDirect === '2' && !isBookkeeping, // 买入显示
            dataIndex: 'price',
            title: '交易价格',
            type: DATA_ENTRY.INPUTNUMBER,
            unit: '元',
            min: 0,
            max: 999999999999,
            initialValue: info ? info.price : undefined,
            splitStyle: true,
            rules: [{ required: true, message: '请输入交易价格!' }],
            onChange: (val) => this.calculateAmount(val, 'parValueTotal'),
            precision: 4,
            disabled,
            span: workStation ? 24 : 12,
          },
          {
            hide: tradeDirect !== '2' || isBookkeeping, // 卖出显示
            dataIndex: 'price',
            title: '净价',
            type: DATA_ENTRY.INPUTNUMBER,
            unit: '元',
            min: 0,
            max: 999999999999,
            initialValue: info ? info.price : undefined,
            splitStyle: true,
            rules: [{ required: true, message: '请输入净价!' }],
            onChange: (val) => this.calculateAmount(val, 'parValueTotal'),
            precision: 4,
            disabled,
            span: workStation ? 24 : 12,
          },
          {
            hide: tradeDirect !== '2' || isBookkeeping, // 卖出显示
            dataIndex: 'interest',
            title: '利息',
            type: DATA_ENTRY.INPUTNUMBER,
            min: 0,
            max: 999999999999,
            initialValue: info ? info.interest : undefined,
            splitStyle: true,
            rules: [{ required: true, message: '请输入利息!' }],
            precision: 4,
            disabled,
            onChange: (val) => this.interestChange(val),
            span: workStation ? 24 : 12,
          },
          {
            dataIndex: 'amount',
            title: '交易数量',
            type: DATA_ENTRY.INPUTNUMBER,
            unit: '份',
            min: 1,
            precision: 2,
            max: 999999999999,
            initialValue: info ? info.amount : undefined,
            splitStyle: true,
            onChange: (val) => this.calculateAmount(val, 'amount'),
            rules: [{ required: true, message: '请输入交易数量!' }],
            disabled,
            span: workStation ? 24 : 12,
          },
          {
            dataIndex: 'parValueTotal',
            title: '交易总额',
            type: DATA_ENTRY.INPUTNUMBER,
            unit: '元',
            min: 0,
            max: 999999999999,
            initialValue: info ? info.parValueTotal : undefined,
            splitStyle: true,
            rules: [{ required: true, message: '请输入交易总额!' }],
            precision: 4,
            disabled: true,
            span: workStation ? 24 : 12,
          },
          {
            hide: tradeDirect !== '2' || isBookkeeping, // 卖出显示
            dataIndex: 'interestArrivalDate',
            title: '利息到账日',
            type: DATA_ENTRY.SINGLEDATE,
            initialValue: info?.interestArrivalDate ? moment(info.interestArrivalDate) : type != '3' && type != '4' ? moment() : undefined,
            disableBegin: moment().add(-1, 'days'),
            rules: [{ required: true, message: '请选择利息到账日!' }],
            disabled,
            allowClear: false,
            span: workStation ? 24 : 12,
          },

          {
            dataIndex: 'zlxdr',
            title: '下达人',
            type: DATA_ENTRY.INPUT,
            initialValue: info ? `${info.userid}-${info.username}` : zlxdr,
            rules: [{ required: true, message: '下达人必填' }],
            disabled: true,
            span: workStation ? 24 : 12,
          },
          {
            title: '费用',
            dataIndex: 'fee',
            placeholder: '请输入',
            type: DATA_ENTRY.INPUTNUMBER,
            min: 0,
            precision: 2,
            initialValue: type == '3' || type == '4' ? info.fee : '',
            splitStyle: true,
            disabled: !!(type == '3' || type == '4'),
            unit: '元',
            span: workStation ? 24 : 12,
            hide: !(type == 10 || type == 12), // 交易录入和多基金展示费用
          },
          ...(type < 5 || type == 12
            ? [
                {
                  // 业务目标
                  dataIndex: 'bussinessObjectives',
                  type: DATA_ENTRY.BUSINESSTARGETC,
                  disabled: !!(type == '3' || type == '4'),
                  initialValue: type == '3' || type == '4' ? info?.bussinessObjectives : undefined,
                  onChangeFn: this.changeObjectives,
                  TaretType: type,
                  info: this.state.editContent,
                  getLayerValue: this.getObjectEdit,
                  span: 24,
                },
                {
                  dataIndex: 'SPPI_result',
                  type: DATA_ENTRY.SPPIRESULTC,
                  title: 'SPPI结果',
                  initialValue: type == '3' || type == '4' ? info.sppiResult : undefined,
                  selectProps: {
                    SecuritiesCode,
                    rightContentShow: !!(type < 3 || type == 12), // 右侧按钮是否展示，后面展示后的禁用逻辑，展示逻辑，组件控制
                    SPPI_result, // 根据证券代码切换获取SPPI结果
                    SppItype: 3,
                    sppITitle: '新增测试',
                  },
                  onOk: this.getSPPI_Result, // 新增完了 重新获取结果
                  span: workStation ? 24 : 12,
                },
                {
                  dataIndex: 'investmentType',
                  type: DATA_ENTRY.SELECT,
                  title: '投资类型',
                  disabled: type == '3' || type == '4' ? true : this.state.tradeDirect == 2,
                  initialValue: type == '3' || type == '4' ? info.investmentType : undefined,
                  dataSource: investmentTypeList,
                  span: workStation ? 24 : 12,
                },
              ]
            : []),
          ...((type < 5 || type == 12) && tenant == 'XAYH'
            ? [
                {
                  dataIndex: 'userDefinedType',
                  type: DATA_ENTRY.SELECT,
                  title: '自定义分类',
                  disabled: !!(type == '3' || type == '4'),
                  initialValue: type == '3' || type == '4' ? info.userDefinedType : undefined,
                  dataSource: SPPI_USER_DEFINEDTYPE.map((item) => {
                    return { value: item.code, title: item.value };
                  }),
                  span: workStation ? 24 : 12,
                },
              ]
            : []),
          {
            dataIndex: 'remark',
            type: DATA_ENTRY.INPUT,
            title: '备注',
            disabled,
            initialValue: info ? info.remark : undefined,
            placeholder: '请输入',
            showTextArea: true,
            autosize: { minRows: 2, maxRows: 2 },
            span: 24,
          },
        ]}
        autoLayout={false}
        onRef={(ref) => {
          this.formGroupRef.current = ref; // formgroup本身
        }}
      />
    );
  };

  // 存储每一个业绩目标对应的补充编辑
  getObjectEdit = (objectivesEditObj) => {
    this.setState({
      objectivesEditObj,
    });
  };

  render() {
    return <div className={style.info}>{this.formRender()}</div>;
  }
}
export default connect(({ nonstandardOrderM, globalM, userM: user, loading, bondTradeM }) => ({
  nonstandardOrderM,
  globalM,
  user,
  loading,
  bondTradeM,
}))(OrderFormC);
